import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';

(function (window, document, $) {
    let _vm, getMainInfo;
    const _json = Utils.ParsingUrl(window.location);
    const paymentTemplate = doT.template($('#payment-template').text());

    $(function () {
        _vm = new Vue({
            el: "#paymentorders-form",
            data() {
                return {
                    "orderId": "",
                    "predictAmount": 0,
                    "settlementPayment": 0,
                    "remark": "",
                    "attaches": "",
                    uploadCount: 0,
                    images: [],//处理weui自带上传插件回显重新上传时的问题
                }
            },
            methods: {
                submit() {
                    savedata()
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand()
        uploadInit();
    });

    //命令初始化
    const _initCommand = () => {
        getMainInfo = JSON.parse(Utils.GetSessionStorage("getMainInfo"));
        $('#paymentorders').empty().append(paymentTemplate(getMainInfo));

        if (_json.isAdvance == "true") {
            $("title").text("预收款-编辑");
            saleOrdersAPI.getOrderAdvances(_json.id).then(res => {
                $('#predictAmount').val(res?.predictAmount)
                $('#settlementPayment').val(res?.settlementPayment)
                $('#payreamrk').val(res?.reamrk)
                if (Utils.IsNotNull(res.attaches)) {
                    _images(res.attaches)
                }
            });
        } else {
            $("title").text("预收款-新增");
        }
        //提交
        $('#informationSubmit').on('click', function () {
            //保留两位小数
            const FLOAT_Method = /^[0-9]+(\.\d{1,2})?$/;

            if (!Utils.IsNotNull($(`#predictAmount`).val())) {
                return $.toptip(`预收款金额不能为空!`, 'warning');
            }
            if (!FLOAT_Method.test($('#predictAmount').val())) {
                return $.toptip(`预收款金额必须大于0且小数点后最多为两位!`, 'warning');
            }
            //if (Number(getMainInfo[0].totalPrice) < Number($('#predictAmount').val())) {
            //    return $.toptip(`预收款金额不能大于总金额!`, 'warning');
            //}
            if (Utils.IsNotNull($('#settlementPayment').val())) {
                if (!FLOAT_Method.test($('#settlementPayment').val())) {
                    return $.toptip(`结算收款金额必须大于0且小数点后最多为两位!`, 'warning');
                }
            }
            if (Number(getMainInfo[0].totalPrice) < Number($('#settlementPayment').val())) {
                return $.toptip(`结算收款金额不能大于总金额!`, 'warning');
            }

            let _attaches = [];
            $.each(_vm.images, function (i, v) {
                _attaches.push(v.imageId);
            });
            if (_json.isAdvance == "true") {
                let putParam = {
                    "predictAmount": $('#predictAmount').val(),
                    "settlementPayment": $('#settlementPayment').val(),
                    "remark": $('#payreamrk').val(),
                    "attaches": _attaches.join(',')
                }
                saleOrdersAPI.updateOrderAdvances(_json.id,putParam).then(res => {
                    $.toptip('请求成功。', 'success');
                    location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                });
            } else {
                let addParam = {
                    "orderId": _json.id,
                    "predictAmount": $('#predictAmount').val(),
                    "settlementPayment": $('#settlementPayment').val(),
                    "remark": $('#payreamrk').val(),
                    "attaches": _attaches.join(',')
                }
                saleOrdersAPI.postOrderadvances(addParam).then(res => {
                    $.toptip('请求成功。', 'success');
                    location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                });
            }
        });
        //取消
        $('#returnMain').on('click', function () {
            location.href = `./saleorders.html?v=${Utils.GetTime()} `;
        });
    }

    //TODO : 附件上传
    //create周润玉
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    /**
     *@file 附件上传
     *@create周润玉
    */
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(res => {
            if (res.isSucceed) {
                let _list = _vm.images;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: upFiles.url,
                    name: newName,
                });
                _vm.images = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.images[i].id);
                    $(this).attr('data-image-id', _vm.images[i].imageId);
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-suffix', _vm.images[i].type);
                    $(this).attr('data-url', _vm.images[i].url);
                    $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                $.hideLoading();
                $.closeModal();
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }

    //TODO : 附件信息回显
    //create周润玉  
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    _vm.images.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (["jpg", "jpeg", "png", 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;

                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

})(window, document, jQuery)